package com.bai.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.bai.base.exceptionHandler.BaiException;
import com.bai.utils.R;
import com.bai.vod.Utils.ConstantVodUtils;
import com.bai.vod.Utils.InitVodClnet;
import com.bai.vod.service.VodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vendorService;

    //TODO:上传视频
    @PostMapping("uploadAlyiVideo")
    public R uploadVideo(MultipartFile file) {
        String videoId = vendorService.uploadVideoAly(file);
        return R.ok().data("videoId", videoId);
    }

    //TODO:删除视频
    @DeleteMapping("removeAlyVideo/{id}")
    public R removeVideo(@PathVariable String id) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClnet.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request里面设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            return R.ok();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new BaiException(2001, "删除视频失败");
        }
    }

    //TODO:删除多个
    @DeleteMapping("/delete-batch")
    public R deleteBatch(@RequestBody List<String> videoIdList) {
        vendorService.reomveMoreAlyVideo(videoIdList);
        return R.ok();
    }

    //TODO:根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            //创建初始化方法
            DefaultAcsClient client
                    = InitVodClnet.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //设置视频id
            request.setVideoId(id);
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth", playAuth);
        } catch (Exception e) {
            throw new BaiException(2001, "获取视频凭证失败");
        }
    }


}
